<template>
  <div class="container">
    <div>
      <el-card v-loading="loading">
        <div class="title-box">
          <h3 class="questions-new-title">{{cardTitle}}</h3>
        </div>

        <el-form
          ref="questionAddForm"
          label-width="150px"
          :model="questionNewForm"
          :rules="riles"
        >
          <el-form-item label="学科：" prop="subjectID">
            <el-select
              v-model="questionNewForm.subjectID"
              style="width: 400px"
              @change="handleSecondaryDirectoryList"
            >
              <el-option
                v-for="item in subjectList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="目录：" prop="catalogID">
            <el-select v-model="questionNewForm.catalogID" style="width: 400px">
              <el-option
                v-for="item in catalogList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="企业：" prop="enterpriseID">
            <el-select
              v-model="questionNewForm.enterpriseID"
              style="width: 400px"
            >
              <el-option
                v-for="item in companyList"
                :key="item.id"
                :label="item.company"
                :value="item.id"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="城市：" prop="city">
            <el-select
              @change="handleCity"
              v-model="questionNewForm.province"
              style="width: 200px"
            >
              <el-option
                v-for="(item, index) in provinceList"
                :key="index"
                :label="item"
                :value="index"
              />
            </el-select>
            <el-select v-model="questionNewForm.city" style="width: 200px">
              <el-option
                v-for="(item, index) in provinceList"
                :key="index"
                :label="item"
                :value="item"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="方向：" prop="direction">
            <el-select v-model="questionNewForm.direction" style="width: 400px">
              <el-option
                v-for="(item, index) in direction"
                :key="index"
                :label="item"
                :value="item"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="题型：">
            <el-radio
              v-for="item in questionType"
              :key="item.value"
              v-model="questionNewForm.questionType"
              :label="`${item.value}`"
            >{{ item.label }}</el-radio>
          </el-form-item>

          <el-form-item label="难度：">
            <el-radio
              v-for="item in difficulty"
              :key="item.value"
              v-model="questionNewForm.difficulty"
              :label="`${item.value}`"
            >{{ item.label }}</el-radio>
          </el-form-item>

          <el-form-item label="题干：" prop="question">
            <vue-editor v-model="questionNewForm.question" />
          </el-form-item>

          <!-- 单选 -->
          <el-form-item
            label="选项："
            class="option"
            v-if="questionNewForm.questionType === '1'"
          >
            <el-radio-group
              v-model="isChoose"
              class="radio-group"
              @change="handleRadioChange"
            >
              <el-row v-for="item in questionNewForm.options" :key="item.code">
                <el-radio :label="item.code">
                  {{ item.code }}：
                  <el-input style="width: 220px" v-model="item.title" />
                  <ImgUpload ref="ImgUpload" />

                </el-radio>
              </el-row>
              <el-row>
                <el-button
                  type="danger" size="small" disabled
                >+增加选项与答案</el-button>
              </el-row>
            </el-radio-group>
          </el-form-item>

          <!-- 多选 -->
          <el-form-item
            label="选项："
            class="option"
            v-if="questionNewForm.questionType === '2'"
          >
            <el-checkbox-group
              @change="handleCheckboxChange"
              v-model="isChoices"
              class="radio-group"
            >
              <el-row v-for="item in questionNewForm.options" :key="item.code">
                <el-checkbox
                  :label="item.code"
                >{{ item.code }}：
                  <el-input style="width: 220px" v-model="item.title" />
                  <ImgUpload ref="ImgUpload" />
                </el-checkbox>
              </el-row>
              <el-row>
                <el-button
                  type="danger" size="small" @click="addCheckbox"
                >+增加选项与答案</el-button>
              </el-row>
            </el-checkbox-group>
          </el-form-item>

          <el-form-item label="解析视频：">
            <el-input v-model="questionNewForm.videoURL" style="width: 400px" />
          </el-form-item>

          <el-form-item label="答案解析：" prop="answer">
            <vue-editor v-model="questionNewForm.answer" />
          </el-form-item>

          <el-form-item label="题目备注：">
            <el-input v-model="questionNewForm.remarks" style="width: 400px" />
          </el-form-item>

          <el-form-item label="试题标签：">
            <!-- multiple -->
            <el-select
              v-model="questionNewForm.tags"
              multiple
              style="width: 400px"
              placeholder="请选择"
            >
              <el-option
                v-for="item in tagList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item>
            <el-button :type="buttonColor" @click="submitForm">确认提交</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
  </div>
</template>

<script>

// 富文本编辑器
import { VueEditor } from 'vue2-editor'

import { detail, add, update } from '@/api/hmmm/questions'
import { directorySimple } from '@/api/hmmm/directorys.js'
import { list } from '@/api/hmmm/companys.js'
import { tagSimple } from '@/api/hmmm/tags.js'
import { difficulty, questionType, direction } from '@/api/hmmm/constants'
import { provinces, citys } from '@/api/hmmm/citys'
import { simple } from '@/api/hmmm/subjects.js'
import ImgUpload from '../components/imageUpload'
export default {
  name: 'questions-new',
  components: {
    ImgUpload,
    VueEditor
  },
  data () {
    return {
      subjectList: [], // 学科列表
      provinceList: [], // 省份列表
      cityList: [], // city 列表
      catalogList: [], // 目录列表
      tagList: [], // 标签列表
      companyList: [], // 企业列表
      isMultiple: false, // 是否多选
      questionNewForm: {
        subjectID: '', // 学科ID
        catalogID: '', // 目录ID
        enterpriseID: '', // 企业简称
        province: '', // 省
        city: '', // 市
        direction: '', // 方向
        questionType: '1', // 题型
        difficulty: '1', // 难度
        question: '', // 题干
        options: [
          { code: 'A', title: '', img: '', isRight: '' },
          { code: 'B', title: '', img: '', isRight: '' },
          { code: 'C', title: '', img: '', isRight: '' },
          { code: 'D', title: '', img: '', isRight: '' }
        ],
        videoURL: '', // 视频URL
        answer: '', // 答案解析
        remarks: '', // 题目备注
        tags: [] // 试题标签
      },
      isChoose: '', // 单选
      loading: false,
      isChoices: [], // 多选
      riles: {
        subjectID: [
          { required: true, message: '请选择学科', trigger: ['change', 'blur'] }
        ],
        catalogID: [
          { required: true, message: '请选择目录', trigger: ['change', 'blur'] }
        ],
        enterpriseID: [
          { required: true, message: '请选择企业', trigger: ['change', 'blur'] }
        ],
        city: [
          { required: true, message: '请选择城市', trigger: ['change', 'blur'] }
        ],
        direction: [
          { required: true, message: '请选择方向', trigger: ['change', 'blur'] }
        ],
        question: [
          { required: true, message: '请输入题干', trigger: ['change', 'blur'] }
        ],
        answer: [
          { required: true, message: '请输入答案解析', trigger: ['change', 'blur'] }
        ]
      }
    }
  },
  created () {
    this.handleRadioChange()
    this.provinceList = provinces()
    this.getSubjectsSimpleList()
    this.getCompanyList()
    this.isRouterId()
  },
  computed: {
    difficulty () {
      return difficulty
    },
    questionType () {
      return questionType
    },
    direction () {
      return direction
    },
    routerId () {
      return this.$route.query.id
      // return 20
    },
    cardTitle () {
      return this.routerId ? '试题修改' : '试题录入'
    },
    buttonColor () {
      return this.routerId ? 'success' : 'primary'
    }
  },
  methods: {
    // 判断进来的时候是否有id
    isRouterId () {
      if (this.routerId) {
        this.getSubjectsInfo()
      }
    },
    // 单选框变化的时候 options.isRight 变化
    handleRadioChange () {
      // console.log(this.isChoose)
      this.questionNewForm.options.forEach(item => {
        if (item.code === this.isChoose) {
          item.isRight = '1'
        } else {
          item.isRight = '0'
        }
      })
      // console.log(this.questionNewForm.options)
    },
    // 多选框变化的时候 options.isRight 变化
    handleCheckboxChange () {
      this.questionNewForm.options.forEach(item => {
        if (this.isChoices.includes(item.code)) {
          item.isRight = '1'
        } else {
          item.isRight = '0'
        }
      })
    },
    // 获取省份下城市
    handleCity () {
      const cityList = citys(this.questionNewForm.provinces)
      this.cityList = cityList
    },
    // 学科列表
    async getSubjectsSimpleList () {
      const res = await simple()
      this.subjectList = res.data
    },
    // 获取二级目录和标签
    async handleSecondaryDirectoryList () {
      // 二级目录
      const res = await directorySimple({
        subjectID: this.questionNewForm.subjectID
      })
      this.catalogList = res.data

      // 标签
      const resTags = await tagSimple({ subjectID: this.questionNewForm.subjectID })

      this.tagList = resTags.data
    },
    // 企业列表
    async getCompanyList () {
      const { data: { items } } = await list({ pagesize: 99999 })
      this.companyList = items
    },
    // 添加
    submitForm () {
      this.$refs.questionAddForm.validate(async (valid) => {
        if (valid) {
          // 处理图片地址
          this.imgUploadFn()
          // 没有routerID就是添加
          if (!this.routerId) {
            // 遍历this.questionData, 属性值为空值空数组的删除
            Object.keys(this.questionNewForm).forEach(key => {
              const val = this.questionNewForm[key]
              if (val === '' || val.length === 0) {
                delete this.questionNewForm[key]
              }
            })

            this.loading = true
            await add(this.questionNewForm)
            this.$message.success('添加成功')
            this.$router.push('/questions/list')
            this.loading = false
          } else {
            // 有routerID就是修改
            this.loading = true
            const res = await update(this.questionNewForm)
            console.log('修改', res)
            this.$message.success('修改成功')
            this.$router.push('/questions/list')
            this.loading = false
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 获取题目详情 用于回显
    async getSubjectsInfo () {
      this.loading = true
      const { data } = await detail({ id: this.routerId })
      this.questionNewForm = data
      // console.log(data.options)
      if (data.questionType === '1') {
        data.options.forEach(item => {
          if (item.isRight === 1) {
            this.isChoose = item.code
          }
        })
      }

      if (data.questionType === '2') {
        data.options.forEach(item => {
          if (item.isRight === 1) {
            this.isChoices.push(item.code)
          }
        })
      }

      // 图片回显
      for (let i = 0; i < data.options.length; i++) {
        const item = data.options
        const refImg = this.$refs.ImgUpload[i]
        if (item[i].img) {
          refImg.fileList.push({
            url: item[i].img,
            uid: +new Date()
          })
        }
        // console.log(item[i].img)
        // console.log(refImg.fileList)
      }

      // console.log(this.isChoices)
      this.loading = false
    },
    // 追加答案
    addCheckbox () {
      const str = String.fromCharCode('A'.charCodeAt() + this.questionNewForm.options.length)
      this.questionNewForm.options.push({
        code: str,
        content: '',
        isRight: '0'
      })
    },
    // 图片上传
    imgUploadFn () {
      const ref = this.$refs.ImgUpload
      const arr = ref.map(item => {
        return item.fileList[0]?.url
      })
      // console.log(arr)
      for (let i = 0; i < this.questionNewForm.options.length; i++) {
        this.questionNewForm.options[i].img = arr[i]
      }
      // console.log(this.questionNewForm.options)
    }

  }
}
</script>

<style scoped lang='scss'>
.title-box {
  height: 40px;
  padding-left: 20px;
  border-bottom: 1px solid #ebeef5;
  margin-bottom: 20px;
  // background-color: #8df;
}
.questions-new-title {
  font-size: 16px;
  font-weight: 400;
  color: #333;
}
::v-deep {
  .el-card__body {
    padding: 0px;
  }
  .el-card {
    // width: 100%;
    padding: 0;
    margin: 15px;
  }
}
.radio-group {
  img {
    width: 100px;
    height: 60px;
    border: 1px solid #333;
  }

  ::v-deep {
    .el-row {
      margin-top: 40px;

      &:first-child {
        margin-top: 0px;
      }
    }
  }
}
::v-deep {
  .quillWrapper {
    width: 98%;
  }
}

</style>
